// text_channel_system.dart
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

class TextChannelSystem extends GetxController {
  TextChannelSystem({this.maxLinesPerChannel = 1000});

  static TextChannelSystem get instance => Get.find();

  // 频道映射，每个频道存储文本行列表
  final Map<String, RxList<String>> _channels = <String, RxList<String>>{}.obs;

  // 当前选中的频道
  final RxString _selectedChannel = ''.obs;

  // 控制状态
  final RxBool _isPaused = false.obs;
  final RxBool _autoScroll = true.obs;

  // 最大存储行数，防止内存溢出
  final int maxLinesPerChannel;

  // 频道列表
  List<String> get channels => _channels.keys.toList();

  RxList<String> get rxChannels => _channels.keys.toList().obs;

  // 当前选中频道
  String get selectedChannel => _selectedChannel.value;

  set selectedChannel(String value) => _selectedChannel.value = value;

  // 是否暂停
  bool get isPaused => _isPaused.value;

  set isPaused(bool value) => _isPaused.value = value;

  // 是否自动滚动
  bool get autoScroll => _autoScroll.value;

  set autoScroll(bool value) => _autoScroll.value = value;

  // 获取指定频道的文本行列表
  RxList<String>? getChannelLines(String channelName) {
    return _channels[channelName];
  }

  // 创建新频道
  void createChannel(String channelName) {
    if (!_channels.containsKey(channelName)) {
      _channels[channelName] = <String>[].obs;
      if (_selectedChannel.isEmpty) {
        _selectedChannel.value = channelName;
      }
    }
  }

  // 向指定频道添加文本行
  void addLineToChannel(String channelName, String line) {
    debugPrint('[$channelName]：$line');
    if (isPaused) return;

    if (!_channels.containsKey(channelName)) {
      createChannel(channelName);
    }

    final channel = _channels[channelName]!;
    // 添加时间
    channel.add('[${DateTime.now().toString().substring(0, 19)}]：$line');

    // 限制最大行数
    if (channel.length > maxLinesPerChannel) {
      channel.removeRange(0, channel.length - maxLinesPerChannel);
    }
  }

  // 清空指定频道
  void clearChannel(String channelName) {
    _channels[channelName]?.clear();
  }

  // 清空所有频道
  void clearAllChannels() {
    _channels.values.forEach((channel) => channel.clear());
  }

  // 删除频道
  void removeChannel(String channelName) {
    _channels.remove(channelName);
    if (_selectedChannel.value == channelName && _channels.isNotEmpty) {
      _selectedChannel.value = _channels.keys.first;
    } else if (_channels.isEmpty) {
      _selectedChannel.value = '';
    }
  }
}
